#Import Modules
import os, pygame
from pygame.locals import *

# Load up our helper functions
from Loaders import *

class AnimatedTile(pygame.sprite.Sprite):
    """this object manages any animated tiles in the level"""
    def __init__(self, name, layer, x, y):
        pygame.sprite.Sprite.__init__(self) #call Sprite initializer

        # Physical Vars
        self.positionx = x
        self.positiony = y
        self.layer = layer
        
        # Animation vars
        self.numframes = 0
        self.currskip = 0
        self.frameskip = 10
        self.animtype = "flip"
        self.frames = list()
        
        # Load up info and frames
        cfgfile = open(os.path.join('data','tiles', name + ".txt"))
        str = cfgfile.read()
        str = str.split('\n')
        
        for line in str:
            setter = line.split('=')
            if setter[0] == "rate":
                self.frameskip = int(setter[1])
            elif setter[0] == "type":
                self.animtype = setter[1]
            elif setter[0] == "frame":
                self.frames.append(load_frame(os.path.join('data','tiles', setter[1] + ".png")))
                self.numframes += 1
        
        # Set up the animation sequence
        self.sequence = range(self.numframes)
        if self.animtype == "bounce" and self.numframes > 2:
            self.sequence.extend(range(self.numframes - 2,0,-1))
        self.sequencestep = 0
        self.sequencelen = len(self.sequence)-1
        
        # Set the initial image
        self.image = self.frames[0]
        self.rect = self.frames[0].get_rect()
        
    def update(self):
        # Update animation frame.
        if self.currskip == self.frameskip:
            self.currskip = 0
            if self.sequencestep < self.sequencelen:
                self.sequencestep += 1
            else:
                self.sequencestep = 0
                
            self.image = self.frames[self.sequence[self.sequencestep]]
            
        else:
            self.currskip += 1